package com.yjn.student.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjn.student.entity.ResultVo;
import com.yjn.student.entity.Student;
import com.yjn.student.service.IStudentService;
import jakarta.annotation.Resource;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/students")
public class StudentController {
    @Resource
    IStudentService studentService;

//    @GetMapping
//    public ResultVo<?> findAllStudent(){
//        List<Student> list = studentService.list();
//        return ResultVo.success(list);
//    }

    @GetMapping
    public ResultVo<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize,
                                @RequestParam(defaultValue = "",required = false) String search){
        Page<Student> page = studentService.page(new Page<>(pageNum,pageSize), Wrappers.<Student>lambdaQuery().like(Student::getStudentname,search));
        return ResultVo.success(page);
    }

    @PostMapping
    public ResultVo<?> save(@RequestBody Student student){
        try {
            studentService.save(student);
            return ResultVo.success("添加成功");
        } catch (Exception e) {
            return ResultVo.error("添加失败");
        }
    }
    
    @PutMapping
    public ResultVo<?> update(@RequestBody Student student){
        try {
            studentService.updateById(student);
            return ResultVo.success("修改成功");
        } catch (Exception e) {
            return ResultVo.error("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    public ResultVo<?> delete(@PathVariable long id){
        try {
            studentService.removeById(id);
            return ResultVo.success("删除成功");
        } catch (Exception e) {
            return ResultVo.error("删除失败");
        }
    }
}
